package com.accompany.fragment.order;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.accompany.R;
import com.accompany.adapter.BaseRecyclerHolder;
import com.accompany.adapter.BaseRecyclerRefreshAdapter;
import com.accompany.api.bean.OrderMesgBean;
import com.accompany.api.category.OrderCategory;
import com.accompany.api.presenter.GrabOrderPresenter;
import com.accompany.api.presenter.OrderPresenter;
import com.accompany.base.BaseBean;
import com.accompany.base.BaseFragment;
import com.accompany.dialog.LoginOutDialog;
import com.accompany.dialog.RoundKefuDialog;
import com.accompany.fragment.login.UserLoginActivity;
import com.accompany.fragment.order.activity.OrderDetialsActivity;
import com.accompany.main.ConstantStaticUrl;
import com.accompany.main.MainActivity;
import com.accompany.utils.HttpNetworkConnectUtils;
import com.accompany.utils.SPUtils;
import com.accompany.utils.ToastUtil;
import com.accompany.view.RecyclerViewLayoutManager;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

import static android.content.Context.MODE_PRIVATE;

/**
 * 信息说明: 待服务
 * company: 兰州丰荣信息科技有限公司
 * 创建时间: on 2022/3/15 16 ：11
 * 项目名称：yuanban
 */
public class ObligationOrderFragment extends BaseFragment implements OrderCategory.View, BaseRecyclerRefreshAdapter.OnItemClickListener, OnRefreshListener, OnLoadMoreListener {
    @BindView(R.id.base_refresh_recycler)
    RecyclerView mRecyclerView;
    @BindView(R.id.relat_empty)
    RelativeLayout mEmptyLayout;
    @BindView(R.id.base_refresh)
    SmartRefreshLayout smartRefreshLayout;
    private String mToken;
    private OrderPresenter mPresenter;
    private long mUserId;
    private BaseRecyclerRefreshAdapter<OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList> mAdapter;
    private List<OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList> mlist = new ArrayList<>();
    private int pageNumber = 1;
    private boolean isLoading =false;
    private LoginOutDialog dialog ;
    private OrderMesgBean baseBean;

    @Override
    public void onResume() {
        super.onResume();
//        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
//        boolean isLogin = sharedPreferences.getBoolean("isLogin",false);
//        if (isLogin){
            smartRefreshLayout.autoRefresh();
//        }else {
//            mEmptyLayout.setVisibility(View.VISIBLE);
//            mRecyclerView.setVisibility(View.GONE);
//        }

    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            smartRefreshLayout.autoRefresh();
        }
    }

    @Override
    public int getLayoutResource() {
        return R.layout.base_refresh_recycler_view;
    }
    @Override
    public void initLayoutView() {

        RecyclerViewLayoutManager.setLinearVerticalManager(getActivity(), mRecyclerView);
        mToken = (String) SPUtils.get(getActivity(), ConstantStaticUrl.mToken, "");
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("First", MODE_PRIVATE);
        mUserId = sharedPreferences.getLong(ConstantStaticUrl.userId, 0);
        mAdapter = new BaseRecyclerRefreshAdapter<OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList>(getActivity(), mlist, R.layout.obl_item_view) {
            @Override
            public void convert(BaseRecyclerHolder holder, OrderMesgBean.OrderMesgBeanData.OrderMesgBeanDataList item, int position, boolean isScrolling) throws IOException {
                holder.setText(R.id.obl_title, "订单号 : " + item.getOrderNo());
                holder.setText(R.id.ordre_price, "￥ " + item.getFinalPrice());
                holder.setText(R.id.fuw_xiagnm, item.getTitle());
                holder.setText(R.id.order_age, item.getOrderDTO().getPatientAge());
                holder.setText(R.id.name, item.getOrderDTO().getPatientName());
                holder.setText(R.id.order_fuwtime, item.getOrderDTO().getPeriodStr());
                TextView gender =  holder.getView(R.id.order_gender);
                    if (item.getOrderDTO().getPatientSex().equals("0")) {
                        gender.setText("女");
                    } else if (item.getOrderDTO().getPatientSex().equals("1")) {
                        gender.setText("男");
                    }
                holder.setText(R.id.service_yiyuan, item.getOrderDTO().getHospitalName());
                holder.setText(R.id.orer_msg, item.getOrderDTO().getRemark());
                holder.getView(R.id.my_dianpin).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        RoundKefuDialog dialog = new RoundKefuDialog(getActivity());
                        dialog.show();
                        TextView mobile = dialog.findViewById(R.id.mobile_number);
                        mobile.setText("0931-8797777");
                        dialog.findViewById(R.id.tv_cancel).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();

                            }
                        });
                        dialog.findViewById(R.id.tv_confirm).setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                // 检查是否获得了权限
                                if (ContextCompat.checkSelfPermission(getActivity(),
                                        Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                                    // 若没有获得授权，申请授权
                                    if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
                                            Manifest.permission.CALL_PHONE)) {
                                        // 如果app之前请求过该权限,被用户拒绝, 这个方法就会返回true.
                                        //  如果用户之前拒绝权限的时候勾选了对话框中”Don’t ask again”的选项,那么这个方法会返回false.
                                        // 如果设备策略禁止应用拥有这条权限, 这个方法也返回false.
                                        // 弹窗需要解释为何需要该权限，再次请求授权
                                        // 帮跳转到该应用的设置界面，让用户手动授权
                                        Intent call = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                        Uri uri = Uri.fromParts("package", getActivity().getPackageName(), null);
                                        call.setData(uri);
                                        startActivity(call);
                                    } else {
                                        // 不需要解释为何需要该权限，直接请求授权
                                        ActivityCompat.requestPermissions(getActivity(),
                                                new String[]{Manifest.permission.CALL_PHONE},
                                                0);
                                    }
                                } else {
                                    // 已经获得授权，可以打电话
                                    // 通过intent跳转到拨打电话的界面
                                    Intent intent1 = new Intent();
                                    intent1.setAction(Intent.ACTION_CALL);
                                    Uri phoneNum = Uri.parse("tel:" + "0931-8797777");
                                    intent1.setData(phoneNum);
                                    startActivity(intent1);
                                }
                                dialog.dismiss();
                            }
                        });
                    }
                });
                //开始服务
                holder.getView(R.id.toserved_msg).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Bundle bundle = new Bundle();
                        bundle.putLong("orderId",mlist.get(position).getId());
                        openActivityWitchAnimation(OrderDetialsActivity.class,bundle);

                    }
                });
            }
        };
        mAdapter.setDatas(mlist);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
        mPresenter = new OrderPresenter(this);
        SetPersenter(mPresenter);
        if (!HttpNetworkConnectUtils.isNetworkConnected(getActivity())) {
            ToastUtil.showToastERROR(getActivity(), "网络不给力,请稍后重试");
        } else {
            mPresenter.getOrderList(pageNumber, mToken, mUserId, 3);
        }
        smartRefreshLayout.setOnRefreshListener(this);
        smartRefreshLayout.setOnLoadMoreListener(this);
    }
    @Override
    public void getOrderList(OrderMesgBean baseBean) {
        this.baseBean = baseBean;
        if (baseBean.getCode() == ConstantStaticUrl.SUCCESS_CODE) {
            if (baseBean.getData() != null && baseBean.getData().getList().size() > 0  ) {
                if (pageNumber == 1) {
                    if (isLoading) {
                        isLoading = false;
                    } else {
                        mlist.clear();
                    }
                    mlist.addAll(baseBean.getData().getList());
                    mAdapter.setDatas(baseBean.getData().getList());
                } else {
                    if (baseBean.getData().isHasNextPage()) {
                        mlist.addAll(mlist.size(), baseBean.getData().getList());
                        mAdapter.add(baseBean.getData().getList());
                        smartRefreshLayout.setEnableLoadMore(true);
                    } else {
//                        ToastUtil.showToastINFO(getActivity(), "没有更多数据");
                        smartRefreshLayout.finishLoadMoreWithNoMoreData();
                    }
                }
                mEmptyLayout.setVisibility(View.GONE);
                mRecyclerView.setVisibility(View.VISIBLE);
            } else {
                if (isLoading) {
                    isLoading = false;
                } else {
                    mEmptyLayout.setVisibility(View.VISIBLE);
                    mRecyclerView.setVisibility(View.GONE);
                }
            }
        }else if (baseBean.getCode() == ConstantStaticUrl.NO_LOGIN_CODE) {
                dialog =  LoginOutDialog.getLoginOutDialog(getActivity() );
            dialog.show();
            dialog.findViewById(R.id.circler_delete).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    dialog.dismiss();
                    dialog = null;
                }
            });
            dialog.findViewById(R.id.to_login).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    openActivityWitchAnimation(UserLoginActivity.class);
                    SPUtils.clear(getActivity());
                    getActivity().finish();
                    dialog.dismiss();
                    dialog = null;
                }
            });

        } else {
            ToastUtil.showToastINFO(getActivity(), baseBean.getMsg());
        }
    }

    @Override
    public void getDeleteOrder(BaseBean baseBean) {

    }

    @Override
    public void SetPersenter(Object persenter) {
    }
    @Override
    public void OnShowErrorMsg(String mErrorMsg) {
        ToastUtil.showToastERROR(getActivity(), mErrorMsg);
    }
    @Override
    public void onItemClick(RecyclerView parent, View view, int position) {
        openActivityWitchAnimation(OrderDetialsActivity.class);
    }


    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        pageNumber = 1;
        mPresenter.getOrderList(pageNumber, mToken, mUserId, 3);
        smartRefreshLayout.finishRefresh(500);
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        if (baseBean.getData().isHasNextPage()) {
            isLoading = true;
            pageNumber++ ;
            mPresenter.getOrderList(pageNumber, mToken, mUserId, 3);
        }else {
            isLoading = false;
        }
        smartRefreshLayout.finishLoadMore(500);

    }
}
